<template>
  <div class="coupon-receive">
    <el-card>
      <div class="table-actions">
        <el-input v-model="search" placeholder="搜索优惠券名称/领用人" style="width: 240px; margin-right: 12px;" clearable />
        <el-button type="primary" @click="exportData">导出数据</el-button>
      </div>
      
      <!-- 多条件搜索区域 -->
      <div class="search-panel">
        <el-form :inline="true" :model="searchForm" class="search-form">
          <el-form-item label="优惠券类型">
            <el-select v-model="searchForm.type" placeholder="全部类型" style="width: 140px;" clearable>
              <el-option label="满减券" value="满减券" />
              <el-option label="折扣券" value="折扣券" />
              <el-option label="包邮券" value="包邮券" />
              <el-option label="无门槛券" value="无门槛券" />
            </el-select>
          </el-form-item>
          <el-form-item label="使用状态">
            <el-select v-model="searchForm.status" placeholder="全部状态" style="width: 140px;" clearable>
              <el-option label="未使用" value="未使用" />
              <el-option label="已使用" value="已使用" />
              <el-option label="已过期" value="已过期" />
              <el-option label="已作废" value="已作废" />
            </el-select>
          </el-form-item>
          <el-form-item label="领取时间">
            <el-date-picker
              v-model="searchForm.receiveDateRange"
              type="daterange"
              range-separator="至"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
              style="width: 240px;"
            />
          </el-form-item>
          <el-form-item label="使用时间">
            <el-date-picker
              v-model="searchForm.useDateRange"
              type="daterange"
              range-separator="至"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
              style="width: 240px;"
            />
          </el-form-item>
          <el-form-item label="面值范围">
            <el-input-number v-model="searchForm.minAmount" placeholder="最小面值" style="width: 120px;" :min="0" />
            <span style="margin: 0 8px;">-</span>
            <el-input-number v-model="searchForm.maxAmount" placeholder="最大面值" style="width: 120px;" :min="0" />
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="handleSearch">搜索</el-button>
            <el-button @click="resetSearch">重置</el-button>
            <el-button type="text" @click="toggleAdvancedSearch">
              {{ showAdvancedSearch ? '收起' : '展开' }}高级搜索
              <el-icon style="margin-left: 4px;">
                <ArrowDown v-if="!showAdvancedSearch" />
                <ArrowUp v-else />
              </el-icon>
            </el-button>
          </el-form-item>
        </el-form>
        
        <!-- 高级搜索区域 -->
        <div v-show="showAdvancedSearch" class="advanced-search">
          <el-form :inline="true" :model="advancedSearchForm" class="search-form">
            <el-form-item label="优惠券来源">
              <el-select v-model="advancedSearchForm.source" placeholder="全部来源" style="width: 140px;" clearable>
                <el-option label="系统自动发放" value="system" />
                <el-option label="用户主动领取" value="user" />
                <el-option label="运营定向发放" value="targeted" />
              </el-select>
            </el-form-item>
            <el-form-item label="用户类型">
              <el-select v-model="advancedSearchForm.userType" placeholder="全部用户" style="width: 140px;" clearable>
                <el-option label="B端客户" value="b" />
                <el-option label="C端客户" value="c" />
              </el-select>
            </el-form-item>
            <el-form-item label="用户等级">
              <el-select v-model="advancedSearchForm.userLevel" placeholder="全部等级" style="width: 140px;" clearable>
                <el-option label="普通用户" value="normal" />
                <el-option label="VIP用户" value="vip" />
                <el-option label="高级用户" value="premium" />
              </el-select>
            </el-form-item>
            <el-form-item label="使用订单">
              <el-input v-model="advancedSearchForm.orderNo" placeholder="订单号" style="width: 180px;" clearable />
            </el-form-item>
            <el-form-item label="过期时间">
              <el-date-picker
                v-model="advancedSearchForm.expireDateRange"
                type="daterange"
                range-separator="至"
                start-placeholder="开始日期"
                end-placeholder="结束日期"
                style="width: 240px;"
              />
            </el-form-item>
          </el-form>
        </div>
      </div>
      
      <el-table :data="pagedList" style="width: 100%; margin-bottom: 12px;">
        <el-table-column type="index" label="序号" width="60" />
        <el-table-column prop="couponId" label="优惠券ID" width="120" />
        <el-table-column prop="couponName" label="优惠券名称" width="180" />
        <el-table-column prop="type" label="优惠券类型" width="100" />
        <el-table-column prop="receiver" label="领用人" width="120" />
        <el-table-column label="面值" width="120">
          <template #default="scope">
            <span v-if="scope.row.type === '满减券'">{{ scope.row.amount }}日元</span>
            <span v-else-if="scope.row.type === '折扣券'">{{ scope.row.discountRate }}折</span>
            <span v-else-if="scope.row.type === '包邮券'">包邮</span>
            <span v-else-if="scope.row.type === '无门槛券'">{{ scope.row.amount }}日元</span>
          </template>
        </el-table-column>
        <el-table-column prop="receiveTime" label="领取时间" width="160" sortable>
          <template #default="scope">
            <span :class="{ 'recent-receive': isRecentReceive(scope.row.receiveTime) }">
              {{ scope.row.receiveTime }}
            </span>
          </template>
        </el-table-column>
        <el-table-column prop="useTime" label="使用时间" width="160">
          <template #default="scope">
            <span v-if="scope.row.useTime">{{ scope.row.useTime }}</span>
            <span v-else>-</span>
          </template>
        </el-table-column>
        <el-table-column prop="expireTime" label="过期时间" width="160" />
        <el-table-column prop="status" label="使用状态" width="100">
          <template #default="scope">
            <el-tag :type="getStatusTagType(scope.row.status)" size="small">
              {{ scope.row.status }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="120" fixed="right">
          <template #default="scope">
            <el-button size="small" type="info" @click="viewDetail(scope.row)">详情</el-button>
          </template>
        </el-table-column>
      </el-table>
      
      <el-pagination
        v-model:current-page="page.current"
        v-model:page-size="page.size"
        :total="filteredList.length"
        layout="total, sizes, prev, pager, next, jumper"
        :page-sizes="[10, 20, 50, 100]"
        style="margin-top: 12px; text-align: right;"
      />
      
      <!-- 详情弹窗 -->
      <el-dialog v-model="detailDialog.visible" :title="`优惠券领取详情 - ${detailDialog.data.couponName}`" width="600px">
        <div class="detail-content">
          <el-descriptions :column="2" border>
            <el-descriptions-item label="优惠券ID">{{ detailDialog.data.couponId }}</el-descriptions-item>
            <el-descriptions-item label="优惠券名称">{{ detailDialog.data.couponName }}</el-descriptions-item>
            <el-descriptions-item label="优惠券类型">{{ detailDialog.data.type }}</el-descriptions-item>
            <el-descriptions-item label="面值">
              <span v-if="detailDialog.data.type === '满减券'">{{ detailDialog.data.amount }}日元</span>
              <span v-else-if="detailDialog.data.type === '折扣券'">{{ detailDialog.data.discountRate }}折</span>
              <span v-else-if="detailDialog.data.type === '包邮券'">包邮</span>
              <span v-else-if="detailDialog.data.type === '无门槛券'">{{ detailDialog.data.amount }}日元</span>
            </el-descriptions-item>
            <el-descriptions-item label="领用人">{{ detailDialog.data.receiver }}</el-descriptions-item>
            <el-descriptions-item label="用户类型">{{ getUserTypeText(detailDialog.data.userType) }}</el-descriptions-item>
            <el-descriptions-item label="用户等级">{{ getUserLevelText(detailDialog.data.userLevel) }}</el-descriptions-item>
            <el-descriptions-item label="领取时间">{{ detailDialog.data.receiveTime }}</el-descriptions-item>
            <el-descriptions-item label="使用时间">{{ detailDialog.data.useTime || '-' }}</el-descriptions-item>
            <el-descriptions-item label="过期时间">{{ detailDialog.data.expireTime }}</el-descriptions-item>
            <el-descriptions-item label="使用状态">
              <el-tag :type="getStatusTagType(detailDialog.data.status)" size="small">
                {{ detailDialog.data.status }}
              </el-tag>
            </el-descriptions-item>
            <el-descriptions-item label="使用订单" :span="2">{{ detailDialog.data.orderNo || '-' }}</el-descriptions-item>
            <el-descriptions-item label="优惠券来源" :span="2">{{ getSourceText(detailDialog.data.source) }}</el-descriptions-item>
          </el-descriptions>
        </div>
      </el-dialog>
    </el-card>
  </div>
</template>

<script setup lang="ts">
import { ref, computed } from 'vue'
import { ElMessage } from 'element-plus'
import { ArrowDown, ArrowUp } from '@element-plus/icons-vue'

// 搜索表单数据
const searchForm = ref({
  type: '',
  status: '',
  receiveDateRange: [],
  useDateRange: [],
  minAmount: null,
  maxAmount: null
})

// 高级搜索表单数据
const advancedSearchForm = ref({
  source: '',
  userType: '',
  userLevel: '',
  orderNo: '',
  expireDateRange: []
})

// 高级搜索显示状态
const showAdvancedSearch = ref(false)

// 详情弹窗数据
const detailDialog = ref({
  visible: false,
  data: {
    couponId: '',
    couponName: '',
    type: '',
    receiver: '',
    amount: 0,
    discountRate: 0,
    receiveTime: '',
    useTime: '',
    expireTime: '',
    status: '',
    userType: '',
    userLevel: '',
    orderNo: '',
    source: ''
  }
})

// 优惠券领取记录接口
interface CouponReceiveRecord {
  id: string
  couponId: string
  couponName: string
  type: string
  receiver: string
  amount: number
  discountRate: number
  receiveTime: string
  useTime: string
  expireTime: string
  status: string
  userType: string
  userLevel: string
  orderNo: string
  source: string
}

// 模拟数据
const receiveList = ref<CouponReceiveRecord[]>([
  {
    id: '6',
    couponId: '1005',
    couponName: '单品特惠券',
    type: '满减券',
    receiver: '孙八',
    amount: 50,
    discountRate: 0,
    receiveTime: '2024-06-06 12:00:00',
    useTime: '',
    expireTime: '2024-07-31 23:59:59',
    status: '未使用',
    userType: 'c',
    userLevel: 'normal',
    orderNo: '',
    source: 'user'
  },
  {
    id: '5',
    couponId: '1004',
    couponName: '无门槛券',
    type: '无门槛券',
    receiver: '钱七',
    amount: 10,
    discountRate: 0,
    receiveTime: '2024-06-05 08:30:00',
    useTime: '2024-06-07 19:45:00',
    expireTime: '2024-06-08 23:59:59',
    status: '已使用',
    userType: 'b',
    userLevel: 'vip',
    orderNo: 'ORD202406070003',
    source: 'targeted'
  },
  {
    id: '4',
    couponId: '1003',
    couponName: '夏日折扣券',
    type: '折扣券',
    receiver: '赵六',
    amount: 0,
    discountRate: 8.8,
    receiveTime: '2024-06-04 13:20:00',
    useTime: '',
    expireTime: '2024-06-04 15:20:00',
    status: '已过期',
    userType: 'c',
    userLevel: 'normal',
    orderNo: '',
    source: 'user'
  },
  {
    id: '3',
    couponId: '1002',
    couponName: '全场包邮券',
    type: '包邮券',
    receiver: '王五',
    amount: 0,
    discountRate: 0,
    receiveTime: '2024-06-03 16:45:00',
    useTime: '2024-06-08 11:30:00',
    expireTime: '2024-06-10 23:59:59',
    status: '已使用',
    userType: 'b',
    userLevel: 'premium',
    orderNo: 'ORD202406080002',
    source: 'targeted'
  },
  {
    id: '2',
    couponId: '1001',
    couponName: '新用户满减券',
    type: '满减券',
    receiver: '李四',
    amount: 20,
    discountRate: 0,
    receiveTime: '2024-06-02 09:15:00',
    useTime: '',
    expireTime: '2024-06-30 23:59:59',
    status: '未使用',
    userType: 'c',
    userLevel: 'vip',
    orderNo: '',
    source: 'system'
  },
  {
    id: '1',
    couponId: '1001',
    couponName: '新用户满减券',
    type: '满减券',
    receiver: '张三',
    amount: 20,
    discountRate: 0,
    receiveTime: '2024-06-01 10:30:00',
    useTime: '2024-06-05 14:20:00',
    expireTime: '2024-06-30 23:59:59',
    status: '已使用',
    userType: 'c',
    userLevel: 'normal',
    orderNo: 'ORD202406050001',
    source: 'user'
  }
])

const search = ref('')
const page = ref({ current: 1, size: 10 })

const filteredList = computed(() => {
  let result = receiveList.value
  
  // 基础搜索（优惠券名称/领用人）
  if (search.value) {
    result = result.filter(item => 
      item.couponName.includes(search.value) || 
      item.receiver.includes(search.value)
    )
  }
  
  // 多条件搜索
  if (searchForm.value.type) {
    result = result.filter(item => item.type === searchForm.value.type)
  }
  
  if (searchForm.value.status) {
    result = result.filter(item => item.status === searchForm.value.status)
  }
  
  // 领取时间范围搜索
  if (searchForm.value.receiveDateRange && searchForm.value.receiveDateRange.length === 2) {
    const startDate = new Date(searchForm.value.receiveDateRange[0])
    const endDate = new Date(searchForm.value.receiveDateRange[1])
    endDate.setHours(23, 59, 59, 999)
    
    result = result.filter(item => {
      const receiveDate = new Date(item.receiveTime)
      return receiveDate >= startDate && receiveDate <= endDate
    })
  }
  
  // 使用时间范围搜索
  if (searchForm.value.useDateRange && searchForm.value.useDateRange.length === 2) {
    const startDate = new Date(searchForm.value.useDateRange[0])
    const endDate = new Date(searchForm.value.useDateRange[1])
    endDate.setHours(23, 59, 59, 999)
    
    result = result.filter(item => {
      if (!item.useTime) return false
      const useDate = new Date(item.useTime)
      return useDate >= startDate && useDate <= endDate
    })
  }
  
  // 面值范围搜索
  if (searchForm.value.minAmount !== null) {
    result = result.filter(item => item.amount >= (searchForm.value.minAmount || 0))
  }
  
  if (searchForm.value.maxAmount !== null) {
    result = result.filter(item => item.amount <= (searchForm.value.maxAmount || 0))
  }
  
  // 高级搜索
  if (advancedSearchForm.value.source) {
    result = result.filter(item => item.source === advancedSearchForm.value.source)
  }
  
  if (advancedSearchForm.value.userType) {
    result = result.filter(item => item.userType === advancedSearchForm.value.userType)
  }
  
  if (advancedSearchForm.value.userLevel) {
    result = result.filter(item => item.userLevel === advancedSearchForm.value.userLevel)
  }
  
  if (advancedSearchForm.value.orderNo) {
    result = result.filter(item => item.orderNo && item.orderNo.includes(advancedSearchForm.value.orderNo))
  }
  
  // 过期时间范围搜索
  if (advancedSearchForm.value.expireDateRange && advancedSearchForm.value.expireDateRange.length === 2) {
    const startDate = new Date(advancedSearchForm.value.expireDateRange[0])
    const endDate = new Date(advancedSearchForm.value.expireDateRange[1])
    endDate.setHours(23, 59, 59, 999)

    result = result.filter(item => {
      const expireDate = new Date(item.expireTime)
      return expireDate >= startDate && expireDate <= endDate
    })
  }

  // 按领取时间倒序排序（最新的在前面）
  result = result.sort((a, b) => {
    const timeA = new Date(a.receiveTime).getTime()
    const timeB = new Date(b.receiveTime).getTime()
    return timeB - timeA // 倒序：新的在前
  })

  return result
})

const pagedList = computed(() => {
  const start = (page.value.current - 1) * page.value.size
  return filteredList.value.slice(start, start + page.value.size)
})

// 搜索方法
function handleSearch() {
  page.value.current = 1
}

// 重置搜索
function resetSearch() {
  search.value = ''
  searchForm.value = {
    type: '',
    status: '',
    receiveDateRange: [],
    useDateRange: [],
    minAmount: null,
    maxAmount: null
  }
  advancedSearchForm.value = {
    source: '',
    userType: '',
    userLevel: '',
    orderNo: '',
    expireDateRange: []
  }
  page.value.current = 1
}

// 切换高级搜索显示
function toggleAdvancedSearch() {
  showAdvancedSearch.value = !showAdvancedSearch.value
}

// 获取状态标签类型
function getStatusTagType(status: string): string {
  const statusMap: Record<string, string> = {
    '未使用': 'info',
    '已使用': 'success',
    '已过期': 'warning',
    '已作废': 'danger'
  }
  return statusMap[status] || 'info'
}

// 获取用户类型文本
function getUserTypeText(userType: string): string {
  const typeMap: Record<string, string> = {
    'b': 'B端客户',
    'c': 'C端客户'
  }
  return typeMap[userType] || userType
}

// 获取用户等级文本
function getUserLevelText(userLevel: string): string {
  const levelMap: Record<string, string> = {
    'normal': '普通用户',
    'vip': 'VIP用户',
    'premium': '高级用户'
  }
  return levelMap[userLevel] || userLevel
}

// 获取来源文本
function getSourceText(source: string): string {
  const sourceMap: Record<string, string> = {
    'system': '系统自动发放',
    'user': '用户主动领取',
    'targeted': '运营定向发放'
  }
  return sourceMap[source] || source
}

// 判断是否是最近的领取记录（24小时内）
function isRecentReceive(receiveTime: string): boolean {
  const receiveDate = new Date(receiveTime)
  const now = new Date()
  const diffHours = (now.getTime() - receiveDate.getTime()) / (1000 * 60 * 60)
  return diffHours <= 24
}

// 查看详情
function viewDetail(row: CouponReceiveRecord) {
  detailDialog.value.data = { ...row }
  detailDialog.value.visible = true
}

// 导出数据
function exportData() {
  ElMessage.success('数据导出功能开发中...')
}
</script>

<style scoped>
.coupon-receive {
  padding: 16px;
}

.table-actions {
  margin-bottom: 12px;
  display: flex;
  align-items: center;
}

.search-panel {
  margin-bottom: 16px;
  padding: 16px;
  background-color: #f5f7fa;
  border-radius: 4px;
}

.search-form {
  display: flex;
  flex-wrap: wrap;
  gap: 12px;
  align-items: center;
}

.advanced-search {
  margin-top: 16px;
  padding: 16px;
  background-color: #f5f7fa;
  border-radius: 4px;
}

.detail-content {
  padding: 16px 0;
}

.recent-receive {
  color: #409eff;
  font-weight: 500;
}
</style> 